package com.example.testnetwork.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.example.testnetwork.AlarmManager;
import com.example.testnetwork.MyConstants;
import com.example.testnetwork.utils.MyLog;

/**
 * 接收定时任务发送过来的广播，用NetworkInfo API来监测网络状态
 */
public class AlarmCheckNetworkReceiver extends BroadcastReceiver {
    public static long lastSendTime =  0;
    @Override
    public void onReceive(Context context, Intent intent) {

        switch(intent.getAction())
        {
            case MyConstants.ALARM_CHECK_NET: {
                float interval = ( (System.currentTimeMillis() - lastSendTime)/1000 ) / 60.0f;
                lastSendTime = System.currentTimeMillis();
                StringBuffer netIsAvailableTip = new StringBuffer();
                boolean isNetOk = isNetworkAvailable(context);

                if(isNetOk){
                    netIsAvailableTip.append("网络可用(net available)");
                }
                else
                    netIsAvailableTip.append("发现网络不可用(net unavailable)");

                MyLog.i("AlarmCheckNetworkReceiver","isNetOk = "+ netIsAvailableTip+",check interval = "+interval+" min");
                AlarmManager.getInstance(context).startAlarmManagerWorkOnReceiver();
                break;
            }
        }
    }

    /**
     * 检测网络是否连接
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected()) {
                // 当前网络是连接的
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    // 当前所连接的网络可用
                    return true;
                }
            }
        }
        return false;
    }


}